//
//  BindingCardVC.m
//  QoilPublic
//
//  Created by SunChao on 17/9/6.
//  Copyright © 2017年 杨凯. All rights reserved.
//

#import "BindingCardVC.h"
#import "QInvoiceRecordCell.h"
#import "QMakeInvoiceCell.h"
#import "ZHPickView.h"
@interface BindingCardVC ()<UITableViewDelegate,UITableViewDataSource,ZHPickViewDelegate,UITextFieldDelegate>
@property (nonatomic,strong)UITableView *tbView;
@property (nonatomic,strong)UIButton *agreeBtn;
@property (nonatomic,strong)UILabel *textLabel;
@property (nonatomic,assign)int rowNumbers;
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong)NSMutableArray *dataDefaultSource;
//@property(nonatomic,strong)ZHPickView *pickview;
@property(nonatomic,strong)NSIndexPath *indexPath;
@property (nonatomic,copy)NSString *nameString;
@property (nonatomic,copy)NSString *cardTypeString;
@property (nonatomic,copy)NSString *cardNumString;
@property (nonatomic,copy)NSString *codeString;
@property (nonatomic,strong)NSMutableArray *cardArr;
@property (nonatomic,copy)NSString *typeId;

@end

@implementation BindingCardVC
// 数据数组的懒加载
- (NSMutableArray *)cardArr
{
    if (!_cardArr ) {
        _cardArr = [NSMutableArray array];
    }
    return _cardArr;
}
- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSArray *cardsArr = @[@"持卡人姓名",@"卡类型",@"银行卡号",@"验证码"];
    NSArray *cardDefaultArr = @[@"请输入持卡人姓名",@"",@"请输入持卡人卡号",@"请输入验证码"];
   
    self.dataSource = cardsArr.mutableCopy;
    self.dataDefaultSource = cardDefaultArr.mutableCopy;
   NSString *textString = @"请绑定持卡人本人银行卡";
   
    UIView *header =[[UIView alloc]initWithFrame:CGRectMake(0, 10, kScreenWidth, 50)];
   
    UILabel *lab =[QViewUtility createLabelWithFrame:CGRectMake(25, 16, kScreenWidth, 20) font:Ksize13 textAlignment:0 textColor:[QColorUtility defaultDeepGrayColor] text:textString];
    [header addSubview:lab];
   
    self.tbView.tableHeaderView =header;
    self.tbView.tableFooterView.backgroundColor = [UIColor redColor];
    
    //提交
    UIView * footer =[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 100)];
   
    UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.5)];
    lineLabel.backgroundColor  = [UIColor groupTableViewBackgroundColor];
    
    [footer addSubview:lineLabel];
//     footer.backgroundColor = [UIColor blueColor];
    _agreeBtn =[QViewUtility createButtonWithFrame:CGRectMake(40, 35, kScreenWidth - 80, 45) font:Ksize17 title:@"提交" titleColor:[UIColor whiteColor] backgroundColor:[QColorUtility defaultBlueColor]];
    [_agreeBtn addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchUpInside];
    _agreeBtn.layer.cornerRadius = 7;
    _agreeBtn.clipsToBounds = YES;
    [footer addSubview:_agreeBtn];
    NSString *tipString = @"\"温馨提示\": 只能绑定一种提现账户";
    UILabel *label = [QViewUtility createLabelWithFrame:CGRectMake(25, 95, kScreenWidth-50, 20) font:Ksize13 textAlignment:1 textColor:[QColorUtility defaultRedColor] text:tipString];
    [footer addSubview:label];
    self.tbView.tableFooterView = footer;
//    self.tbView.tableFooterView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:self.tbView];
    [self.tbView registerNib:[UINib nibWithNibName:@"QMakeInvoiceCell" bundle:nil] forCellReuseIdentifier:@"QMakeInvoiceCell"];
    [self.tbView registerNib:[UINib nibWithNibName:@"QCustomerOrderCell" bundle:nil] forCellReuseIdentifier:@"QCustomerOrderCell"];
    [self requestBanksData];
}

- (void)submitAction{
    

    [self.view endEditing:YES];
    
    if ([self.nameString isEqualToString:@""]||self.nameString == nil) {
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"请输入持卡人姓名" btnTitle:showAlertBtnTitle type:0 myBlock:^{}];
            return;
        }

    if ([self.cardTypeString isEqualToString:@""]||self.cardTypeString == nil) {
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"请选择银行卡类型" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
            return;
        }
    if ([self.cardNumString isEqualToString:@""]||self.cardNumString == nil) {
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"请输入银行卡号" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
            return;
        }
    if ([self.codeString isEqualToString:@""]||self.codeString == nil) {
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"请输入验证码" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
            return;
        }
    
    for (NSDictionary *tmpDic in self.cardArr) {
        if ([[tmpDic objectForKey:@"name"]isEqualToString:self.cardTypeString]) {
            _typeId = [tmpDic objectForKey:@"typeId"];
        }
    }
    
    [self requestData];
}
- (void)requestBanksData{
    
    NSString *url = [QParamService urlWithAction:@"userinfo/getInitAdd"];
    NSDictionary *para= [QParamService GainALLBanks];
    [QViewUtility showMBHudToView:self.view hideBg:YES];
    [QViewUtility disMissNoRecordInVC:self];
    [QViewUtility disMissNoNetWorkInVC:self];
    [[QHttpManager sharedManager] POST:url parameterMD5:para completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [_tbView.mj_header endRefreshing];
        [QViewUtility hideMBHudToView:self.view];
        if(error){
            if([QUserInfo sharedInfo].isHaveNetWork == NO){
                [QViewUtility showNoNetWorkInView:_tbView];
            }
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            
           NSDictionary *dic = basModel.items;
            
           NSArray *array = [dic objectForKey:@"blanks"];
            [self.cardArr removeAllObjects];
            self.cardArr = array.mutableCopy;
            if (array.count>0) {
                
                NSMutableArray *cardsArr = [NSMutableArray array];
                for (NSDictionary *tmpDic in array) {
                    NSString *name = [tmpDic objectForKey:@"name"];
                    [cardsArr addObject:name];
                }
                NSFileManager *fileManager = [NSFileManager defaultManager];
                NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                NSString *filePath = [docPath stringByAppendingPathComponent:@"cardsPlist.plist"];
                if ([fileManager fileExistsAtPath:filePath] == NO) {
                    NSLog(@"不存在");
                    [self creatPlistFileWithArr:cardsArr];
                    NSArray *plistArr = [NSArray arrayWithContentsOfFile:filePath];
                    NSLog(@"读取 写入的plist 文件:%@",plistArr);
                } else {
                    NSLog(@"存在");
                    [cardsArr writeToFile:filePath atomically:YES];
                    NSArray *plistArr = [NSArray arrayWithContentsOfFile:filePath];
                    NSLog(@"读取 写入的plist 文件:%@",plistArr);
                    
                }
            }else{
               [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"后台返回错误" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
            }
            
            
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
    
}
#pragma mark - 创建plist文件
-(void)creatPlistFileWithArr:(NSArray *)array{
    //将字典保存到document文件->获取appdocument路径
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    //要创建的plist文件名 -> 路径
    NSString *filePath = [docPath stringByAppendingPathComponent:@"cardsPlist.plist"];
    //将数组写入文件
    [array writeToFile:filePath atomically:YES];
    //读取文件
    NSArray *plistArr = [NSArray arrayWithContentsOfFile:filePath];
    NSLog(@"读取 写入的plist 文件:%@",plistArr);
}
- (void)requestData{
   
    NSString *name = self.nameString;
    NSString *cardType = self.typeId;
    NSString *cardNum = self.cardNumString;
    NSString *codeNum = self.codeString;
    
    NSString *url = [QParamService urlWithAction:@"userinfo/getAdd"];
    NSDictionary *params = [QParamService BindingBankWithName:name CardType:cardType CardNum:cardNum Identity:@"" Ramark:@"银行卡绑定测试" Code:codeNum];
    [QViewUtility showMBHudToView:self.view hideBg:YES];
    [QViewUtility disMissNoRecordInVC:self];
    [QViewUtility disMissNoNetWorkInVC:self];
    [[QHttpManager sharedManager] POST:url parameterMD5:params completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [_tbView.mj_header endRefreshing];
        [QViewUtility hideMBHudToView:self.view];
        if(error){
            if([QUserInfo sharedInfo].isHaveNetWork == NO){
                [QViewUtility showNoNetWorkInView:_tbView];
            }
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            
        [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"提交成功" btnTitle:showAlertBtnTitle type:1 myBlock:^{

            [self.navigationController popViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"AddNewCardNotification" object:nil];
        
        }];
        
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
    
}
-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (UITableView*)tbView {
    if (!_tbView) {
        _tbView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
        _tbView.dataSource = self;
        _tbView.delegate = self;
        _tbView.backgroundColor = [UIColor whiteColor];
        _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tbView.bounces = NO;
    }
    return _tbView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 4;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
     NSInteger row = [indexPath row];
    QMakeInvoiceCell * cell= [tableView dequeueReusableCellWithIdentifier:@"QMakeInvoiceCell" forIndexPath:indexPath];
    cell.titleLabe.text =_dataSource[row];
    cell.textField.placeholder  = _dataDefaultSource[row];
    cell.textField.clearButtonMode=UITextFieldViewModeWhileEditing;
    cell.textField.tag = row;
    cell.textField.delegate = self;
    cell.secondLab.hidden = YES;
    cell.thirdLab.hidden = YES;
    cell.codeBtn.hidden = YES;
   
    [cell.textField addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];
    [_pickview remove];
        if (indexPath.row == 0) {
            cell.textField.keyboardType = UIKeyboardTypeDefault;
        }
        else if (indexPath.row ==1) {
            _indexPath = indexPath;
            cell.textField.hidden = YES;
            cell.thirdLab.hidden = NO;
            cell.thirdLab.textAlignment = NSTextAlignmentRight;
            cell.thirdLab.text = @"请选择";
            cell.iconImg.hidden = NO;

        }
        else if (indexPath.row ==2) {
            
        cell.textField.keyboardType = UIKeyboardTypePhonePad;
       
        }
        else if (indexPath.row == 3) {
        _indexPath = indexPath;
        cell.codeBtn.hidden = NO;
        cell.textField.keyboardType = UIKeyboardTypePhonePad;
        [cell setNewFrameWithTextField];
        cell.codeBlock = ^(UIButton *button){
        [QParamService onTimer:button type:NO];
        [self requestCardCode];
        [self.view endEditing:YES];

        };
            
        }
        return cell;
}

#pragma mark-----请求验证码接口
- (void)requestCardCode{
    NSString *url = [QParamService urlWithAction:@"getVerificationCode"];
    NSDictionary *param = [QParamService getCardCode];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"验证码已发送,请注意查收" btnTitle:showAlertBtnTitle type:1 myBlock:^{ }];
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [_pickview remove];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
     [self.tbView resignFirstResponder];
    _indexPath=indexPath;
    [_pickview remove];
    if (indexPath.row == 1) {
       [self.view endEditing:YES];
        
        _pickview=[[ZHPickView alloc] initPickviewWithPlistName:@"cardsPlist.plist" isHaveNavControler:NO];
        _pickview.delegate=self;
        [_pickview setToolbarTintColor:[UIColor blackColor]];
        [_pickview setTintColor:[UIColor whiteColor]];
        [_pickview setPickViewColer:[UIColor whiteColor]];
        [_pickview changeSpearatorLineColor];
        [_pickview show];
    }
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    [self.tbView endEditing:YES];
}
#pragma mark ZhpickVIewDelegate

-(void)toobarDonBtnHaveClick:(ZHPickView *)pickView resultString:(NSString *)resultString{
    
    QMakeInvoiceCell * cell=[self.tbView cellForRowAtIndexPath:_indexPath];
    cell.secondLab.hidden = NO;
    cell.secondLab.textColor = [UIColor blackColor];
    cell.secondLab.text=resultString;
    self.cardTypeString = resultString;
}
- (void)textFieldWithText:(UITextField *)textField
{
    
    [_pickview remove];
     NSLog( @"text changed: %@", textField.text);
    if (textField.tag == 0) {
        self.nameString = textField.text;
    }
    if (textField.tag == 3) {
        self.codeString = textField.text;
    }
}

#pragma UITextFieldDelegate实现输入四位数出现一个空格
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if ([string isEqualToString:@""]) {
        
        return YES;
    }
     NSString *text = [textField text];
    if (textField.tag == 2) {
    
        NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
        string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
        if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
            return NO;
        }
        text = [text stringByReplacingCharactersInRange:range withString:string];
        text = [text stringByReplacingOccurrencesOfString:@" "withString:@""];
        if ([text length] >= 21) {
            [self.view endEditing:YES];
            return NO;
        }
        
        NSString *newString =@"";
        while (text.length >0) {
            NSString *subString = [text substringToIndex:MIN(text.length,4)];
            newString = [newString stringByAppendingString:subString];
            if (subString.length ==4) {
                newString = [newString stringByAppendingString:@" "];
            }
            text = [text substringFromIndex:MIN(text.length,4)];
        }
        newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
        [textField setText:newString];
        self.cardNumString = textField.text;
        return NO;

        
    }
    
    if (text.length>=19) {
        [self.view endEditing:YES];
        
        return NO;
    }
    if (textField.tag == 3) {
        if (text.length>=6) {
            [self.view endEditing:YES];
            return NO;
        }
    }
    return YES;
}
@end
